// 引入其他的类
import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";

// 游戏控制器
class GameControl {
    // 蛇
    snake: Snake
    // 食物
    food: Food
    // 记分牌
    scorePanel: ScorePanel
    // 创建一个属性来存储蛇的移动方向
    dierction: string = ''
    // 属性判断游戏是否结束
    isLive = true



    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel()

        this.init()
    }
    init() {
        // 绑定事件
        document.addEventListener('keydown', this.keydownHandler.bind(this))
        this.run()
    }
    // 事件响应函数
    keydownHandler(event: KeyboardEvent) {
        // 修改direction  判断key的值
        this.dierction = event.key
    }
    // 操作蛇移动
    run() {
        // 根据按键来使蛇的位置移动
        let X = this.snake.X
        let Y = this.snake.Y


        // 跟据案件方向修改X值和Y值
        switch (this.dierction) {
            case "ArrowUp":
                Y -= 10
                break;
            case "ArrowDown":
                Y += 10
                break;
            case "ArrowLeft":
                X -= 10
                break;
            case "ArrowRight":
                X += 10
                break;
        }

        // 检测蛇是否吃到了食物
        this.checkEat(X, Y)

        try {
            this.snake.X = X
            this.snake.Y = Y
        } catch (error: any) {
            alert(error.message)
            this.isLive = false
        }

        // 开始一个定时调用
        this.isLive && setTimeout(this.run.bind(this), 150 - (this.scorePanel.level - 1) * 15);
    }
    checkEat(X: number, Y: number) {
        if (X === this.food.X && Y === this.food.Y) {
            // 吃到食物位置要进行充值
            this.food.chang()
            // 分数增加
            this.scorePanel.addScore()
            // 蛇的长度增加
            this.snake.addBody()
        }
    }
}

export default GameControl